package com.chuiyuan.study;

import com.chuiyuan.utils.ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by chuiyuan on 3/3/16.
 */
public class CallableDemo {
    public static void main(String [] args ){
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> resultList = new ArrayList<Future<String>>() ;

        for (int i =0;i<10; i++){
            Future<String> future = executorService.submit(new TaskWithResult(i));
            resultList.add(future);
        }

        for (Future<String> fs : resultList){
            try {
                while (!fs.isDone());
                System.out.println(fs.get());
            }catch (InterruptedException e ){
                e.printStackTrace();
            }catch (ExecutionException e){
                e.printStackTrace();
            }finally {
                executorService.shutdown();
            }
        }
    }

}

class TaskWithResult implements Callable<String>{
    private int id ;

    public TaskWithResult(int id){
        this.id = id ;
    }

    public String call() throws Exception {
        System.out.println("call invoke in "+Thread.currentThread().getName());
        //return value to get
        return id+ Thread.currentThread().getName();
    }
}
